package com.aramis.mydytt.ui.recommend

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.aramis.mydytt.R
import com.aramis.mydytt.ui.base.BaseFragment
import com.aramis.mydytt.ui.detail.MovieDetailActivity
import com.aramis.mydytt.ui.recommend.adapter.MainRecommendAdapter
import com.aramis.mydytt.widget.LoadingStateView

/**
 * 推荐Fragment
 */
class MainRecommendFragment : BaseFragment() {
    private lateinit var mainRecommendViewModel: MainRecommendViewModel
    private lateinit var swipeLayout: SwipeRefreshLayout
    private val recommendAdapter = MainRecommendAdapter()
    private var loadingView: LoadingStateView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainRecommendViewModel = createViewModel()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val root = inflater.inflate(R.layout.fragment_main_recommend, container, false)
        initView(root)
        initObserver()
        initData()
        return root
    }

    private fun initObserver() {
        mainRecommendViewModel.movieListData.observe(viewLifecycleOwner, {
            swipeLayout.isRefreshing = false
            loadingView?.showState(it)
            recommendAdapter.setData(it)
        })
    }

    private fun initData() {
        swipeLayout.isRefreshing = true
        mainRecommendViewModel.getRecommendToday()
        mainRecommendViewModel.getMovieTag()
    }

    private fun initView(root: View) {
        val listView: RecyclerView = root.findViewById(R.id.list_main_recommend)
        listView.adapter = recommendAdapter
        listView.layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)

        swipeLayout = root.findViewById(R.id.swipe_main_recommend)
        swipeLayout.setOnRefreshListener {
            mainRecommendViewModel.pullToRefreshMovieList()
        }
        recommendAdapter.onSubItemClickListener = {
            MovieDetailActivity.start(requireActivity(), it)
        }
        loadingView = root.findViewById(R.id.view_loading)
        loadingView?.setOnErrorRetryListener {
            initData()
            loadingView?.dismiss()
        }
    }
}